package com.sky.Service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.Dao.*;
import com.sky.Service.OrderService;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl
        extends ServiceImpl<OrderDao, Orders>
        implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderDetailDao orderDetailDao;
    @Autowired
    private ShoppingCartDao shoppingCartDao;
    @Autowired
    private AddressBookDao addressBookDao;
    @Autowired
    private UserDao userDao;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;


    @Override
    public OrderSubmitVO submitOrderInfo(OrdersSubmitDTO ordersSubmitDTO) {
        //获取当前用户id
        Long currentUserId = getCurrentUserId();
        //处理各种业务异常（购物车为空。地址簿为空）
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, currentUserId)
                .eq(AddressBook::getId, ordersSubmitDTO.getAddressBookId());
        AddressBook addressBook = addressBookDao.selectOne(queryWrapper);
        if (addressBook == null) {
            //地址簿为空
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断购物车是否为空
        LambdaQueryWrapper<ShoppingCart> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(ShoppingCart::getUserId, currentUserId);
        List<ShoppingCart> shoppingCarts = shoppingCartDao.selectList(queryWrapper1);
        if (shoppingCarts == null || shoppingCarts.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表中插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //订单号
        orders.setNumber(UUID.randomUUID().toString());
        //订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        //下单用户
        orders.setUserId(currentUserId);
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //支付状态
        orders.setPayStatus(Orders.UN_PAID);
        //手机号
        orders.setPhone(addressBook.getPhone());
        //地址
        orders.setAddress(addressBook.getDetail());
        //收货人
        orders.setConsignee(addressBook.getConsignee());
        System.out.println("插入的订单信息:"+orders);
        //保存订单信息
        orderDao.insert(orders);
        //向订单明细表中插入多条数据
        shoppingCarts.stream().forEach(item -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item, orderDetail, "userId");
            orderDetail.setOrderId(orders.getId());
            orderDetailDao.insert(orderDetail);
        });
        //清空购物车数据
        shoppingCartDao.delete(queryWrapper1);
        //封装返回对象
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        return orderSubmitVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long currentUserId = getCurrentUserId();
        User user = userDao.selectById(currentUserId);

//        调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid0
//        );

        JSONObject jsonObject = new JSONObject();

        //code应该是判断用户是否支付的唯一标识
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        //统一下单接口返回的prepay_id参数值，用于后续接口调用中使用
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }


    /**
     * 支付成功，修改订单状态
     * 商户平台订单号
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getNumber, outTradeNo);
        Orders ordersDB = orderDao.selectOne(queryWrapper);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payMethod(1)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        // 更新订单状态
        orderDao.updateById(orders);
        //通过websocket向客户端浏览器推送消息type orderId,content
        HashMap map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号:"+outTradeNo);
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);

    }

    @Override
    public OrderVO getOrderDetail(Long id) {
        Long currentUserId = getCurrentUserId();
        //OrderVO
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, currentUserId)
                .eq(Orders::getId, id);
        Orders order = orderDao.selectOne(queryWrapper);
        if (order != null) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderDetail::getOrderId, order.getId());
            List<OrderDetail> orderDetails = orderDetailDao.selectList(queryWrapper1);
            orderVO.setOrderDetailList(orderDetails);
            return orderVO;
        }
        throw new OrderBusinessException((MessageConstant.ORDER_NOT_FOUND));
    }

    @Override
    public IPage<OrderVO> getHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //获取当前用户id
        Long currentUserId = getCurrentUserId();

        IPage<Orders> page = new Page<>(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, currentUserId)
                .eq(ordersPageQueryDTO.getStatus() != null, Orders::getStatus, ordersPageQueryDTO.getStatus())
                .orderByDesc(Orders::getOrderTime);
        IPage<Orders> ordersIPage = orderDao.selectPage(page, queryWrapper);
        IPage<OrderVO> orderVOPage = new Page<>();
        BeanUtils.copyProperties(ordersIPage, orderVOPage, "records");
        //单独来处理records
        List<Orders> records = ordersIPage.getRecords();
        List<OrderVO> orderVOList = records.stream().map(item -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(item, orderVO);
            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderDetail::getOrderId, item.getId());
            List<OrderDetail> orderDetails = orderDetailDao.selectList(queryWrapper1);
            orderVO.setOrderDetailList(orderDetails);
            return orderVO;
        }).collect(Collectors.toList());
        orderVOPage.setRecords(orderVOList);
        return orderVOPage;
    }

    @Override
    public void cancelUserOrder(Long id) {
        //获取当前用户id
        Long currentUserId = getCurrentUserId();
        //根据订单id查询订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, currentUserId)
                .eq(Orders::getId, id);
        Orders orders = orderDao.selectOne(queryWrapper);
        if (orders != null) {
            //订单状态为待支付或者已支付，才可以取消订单
            if (orders.getStatus().equals(Orders.PENDING_PAYMENT) || orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
                //修改订单状态为取消
                orders.setStatus(Orders.CANCELLED);
                orderDao.updateById(orders);
            } else {
                throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
            }
        }
    }

    @Override
    public IPage<Orders> getQueryByPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<> ();
        IPage<Orders> page=new Page<> (ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //订单状态
        queryWrapper.eq(ordersPageQueryDTO.getStatus()!=null,Orders::getStatus,ordersPageQueryDTO.getStatus())
                  .eq(ordersPageQueryDTO.getNumber()!=null,Orders::getNumber,ordersPageQueryDTO.getNumber())
                  .eq(ordersPageQueryDTO.getPhone()!=null,Orders::getPhone,ordersPageQueryDTO.getPhone())
                  .between(ordersPageQueryDTO.getBeginTime()!=null&&ordersPageQueryDTO.getEndTime()!=null,
                          Orders::getOrderTime,ordersPageQueryDTO.getBeginTime(),ordersPageQueryDTO.getEndTime())
                .orderByDesc(Orders::getOrderTime);

        //订单号
        //手机号
        //下单时间
        IPage<Orders> ordersIPage = orderDao.selectPage(page, queryWrapper);

        return ordersIPage;
    }

    @Override
    public OrderVO getAdminOrderDetail(Long id) {
        //根据订单id查询订单
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<> ();
        queryWrapper.eq(Orders::getId,id);
        Orders orders = orderDao.selectOne(queryWrapper);
        if(orders!=null){
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderDetail::getOrderId,id);
            List<OrderDetail> orderDetails = orderDetailDao.selectList(queryWrapper1);
            orderVO.setOrderDetailList(orderDetails);
            return orderVO;
        }

        return null;
    }

    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {

        //根据订单id查询订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<> ();
        queryWrapper.eq(Orders::getId,ordersConfirmDTO.getId());
        Orders orders = orderDao.selectOne(queryWrapper);
        if(orders!=null){
            //修改订单的状态
            orders.setStatus(Orders.CONFIRMED);
            orderDao.updateById(orders);
        }
    }

    @Override
    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO) {
        //根据订单id查询订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<> ();
        queryWrapper.eq(Orders::getId, ordersRejectionDTO.getId());
        Orders orders = orderDao.selectOne(queryWrapper);
        if(orders!=null){
            //修改订单支付状态
            orders.setPayStatus(Orders.REFUND);
            orders.setStatus(Orders.CANCELLED);
            //设置拒单原因
            orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
            orderDao.updateById(orders);
        }
    }

    @Override
    public void deliveryOrder(Long id) {
        //根据订单id查询订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<> ();
        queryWrapper.eq(Orders::getId, id);
        Orders orders = orderDao.selectOne(queryWrapper);
        if(orders!=null){
            orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
            orderDao.updateById(orders);
        }
    }

    @Override
    public void completeOrder(Long id) {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<> ();
        queryWrapper.eq(Orders::getId, id);
        Orders orders = orderDao.selectOne(queryWrapper);
        if(orders!=null){
            orders.setStatus(Orders.COMPLETED);
            orderDao.updateById(orders);
        }
    }

    @Override
    public void cancelAdminOrder(OrdersCancelDTO ordersCancelDTO) {
        //根据订单id查询订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<> ();
        queryWrapper.eq(Orders::getId, ordersCancelDTO.getId());
        Orders orders = orderDao.selectOne(queryWrapper);
        if(orders!=null){
            orders.setStatus(Orders.CANCELLED);
            orderDao.updateById(orders);
        }

    }

    public Long getCurrentUserId() {
        return BaseContext.getCurrentUserId();
    }
}
